import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  OneToMany,
  OneToOne,
} from 'typeorm';
import { IsEmail, IsNotEmpty, MinLength } from 'class-validator';
import { Post } from './Post';
import { Payment } from './Payment';
import { Subscription } from './Subscription';

@Entity('users')
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ unique: true, nullable: true })
  @MinLength(3, { message: '用户名至少3个字符' })
  username?: string;

  @Column({ unique: true })
  @IsEmail({}, { message: '请输入有效的邮箱地址' })
  email: string;

  @Column({ nullable: true })
  @MinLength(6, { message: '密码至少6个字符' })
  password?: string;

  @Column({ unique: true, nullable: true })
  googleId?: string;

  @Column({ unique: true, nullable: true })
  githubId?: string;

  @Column({ nullable: true })
  picture?: string;

  @Column({ type: 'enum', enum: ['local', 'google', 'github'], default: 'local' })
  provider: 'local' | 'google' | 'github';

  @Column({ nullable: true })
  firstName?: string;

  @Column({ nullable: true })
  lastName?: string;

  @Column({ default: true })
  isActive: boolean;

  @Column({ name: 'stripe_customer_id', nullable: true, unique: true })
  stripeCustomerId?: string;

  @CreateDateColumn()
  createdAt: Date;

  @UpdateDateColumn()
  updatedAt: Date;

  @OneToMany(() => Post, (post) => post.author)
  posts: Post[];

  @OneToMany(() => Payment, (payment) => payment.user)
  payments: Payment[];

  @OneToMany(() => Subscription, (subscription) => subscription.user)
  subscriptions: Subscription[];

  // 积分相关关系（懒加载）
  userCredits?: any; // 延迟导入，避免循环依赖
  creditTransactions?: any; // 延迟导入，避免循环依赖
  designs?: any; // 延迟导入，避免循环依赖

  // 排除敏感字段的方法
  toJSON() {
    const { password, googleId, stripeCustomerId, ...userWithoutSensitiveData } = this;
    return userWithoutSensitiveData;
  }
}